<?php
/**
 * mongoDB文档获取与插入示例
 * Created by PhpStorm.
 * User: zzx
 * Date: 2018/1/18
 * Time: 下午12:15
 */

require 'config.php';
require 'vendor/autoload.php';

// 实例化连接
// 本地
$db = new MongoDB\Client("mongodb://{$cnf['USERNAME']}:{$cnf['PASSWD']}@{$cnf['HOST']}:{$cnf['PORT']}/{$cnf['DBNAME']}");
// 远程
$db_r = new MongoDB\Client("mongodb://root:Zzxx1688..@192.168.1.88:27017/admin");


// 插入一个文档
$collection = $db->test->users;

$insertOneResult = $collection->insertOne([
    'username' => 'admin',
    'email' => 'admin@example.com',
    'name' => 'Admin User',
]);

printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());

var_dump($insertOneResult->getInsertedId());


// 获取远程数据
$coll = "04.scene"; // 注：集合名中带有‘.’，必须放入变量，不能直接使用字符串
$collection_r = $db_r->bim->$coll;

// 获取一个文档
$result = $collection_r->findOne();
var_dump($result);

// 获取所有文档
echo "\n\n########################################################################\n";
$res = $collection_r->find();
foreach ($result as $key => $value) {
    echo 'key：'.$key."\n";
    var_dump($value);
}

// 写入本地数据库
$collection = $db->test->$coll; // 写入test数据库，的同名集合
foreach ($res as $key => $value) {
    $collection->insertOne($value);
}


// 插入多个文档
$collection = $db->test->users2;

$insertManyResult = $collection->insertMany([
    [
        'username' => 'admin',
        'email' => 'admin@example.com',
        'name' => 'Admin User',
    ],
    [
        'username' => 'test',
        'email' => 'test@example.com',
        'name' => 'Test User',
    ],
]);

printf("Inserted %d document(s)\n", $insertManyResult->getInsertedCount());

var_dump($insertManyResult->getInsertedIds());
